package com.hzsoft.util;

import java.io.File;
import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.lang3.StringUtils;

/**
 * 系统工具类
 */
public class SystemUtil {

	/**
	 * 获取客户真实IP地址
	 * @param request 请求对象
	 * @return IP地址字符串
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * 返回MD5码
	 * @param parStr 要编码的字符串
	 * @return 返回值
	 */
	public static String getMD5Code(String parStr) {
		return DigestUtils.md5Hex(parStr);
	}
	
	/**
	 * 返回字节数组MD5码
	 * 例如:可用于返回文件的校验码
	 * @param parByteArray 字节数组
	 * @return 返回值
	 */
	public static String getMD5Code(byte[] parByteArray) {
		return DigestUtils.md5Hex(parByteArray);
	}
	
	/**
	 * 返回SHA码
	 * @param parStr 要编码的字符串
	 * @return 返回值
	 */
	public static String getSHACode(String parStr) {
		return DigestUtils.sha1Hex(parStr);
	}
	
	/**
	 * 返回字节数组SHA码
	 * 例如:可用于返回文件的校验码
	 * @param parByteArray 字节数组
	 * @return 返回值
	 */
	public static String getSHACode(byte[] parByteArray) {
		return DigestUtils.sha1Hex(parByteArray);
	}
	
	/**
	 * URL编码
	 * @param url 编码字符串
	 * @return 返回值
	 */
	public static String urlEncode(String url) {
		URLCodec urlCodec = new URLCodec();
		String endStr = null;
		try {
			endStr = urlCodec.encode(url);
		}
		catch(Exception ex) {
			System.out.println("urlEncode error : " + ex.getMessage());
			ex.printStackTrace();
		}
		return endStr;
	}
	
	/**
	 * URL解码
	 * @param url 解码字符串
	 * @return 返回值
	 */
	public static String urlDecode(String url) {
		URLCodec urlCodec = new URLCodec();
		String endStr = null;
		try {
			endStr = urlCodec.decode(url);
		}
		catch(Exception ex) {
			System.out.println("urlDecode error : " + ex.getMessage());
			ex.printStackTrace();
		}
		return endStr;
	}
	
	/**
	 * 获取本机主机名
	 */
	public static String getLocalHostName() {
		String hostName = null;
		try {
			hostName = InetAddress.getLocalHost().getHostName();
		}
		catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
		return hostName;
	}
	
	/**
	 * 创建目录
	 */
	public static void createDir(String path) {
		if (StringUtils.isEmpty(path)) {
			return;
		}
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
	}
}
